<template>
  <el-button type="success" @click="dialogFormVisible = true">新增</el-button>
  <el-button type="primary" @click="search((showMessage = true))">查询</el-button>
  <el-table
    :data="tableData"
    height="550"
    stripe
    border
    :table-layout="fixed"
    style="width: 100%"
  >
    <el-table-column prop="goodsCode" label="商品编码" />
    <el-table-column prop="goodsName" label="商品名称" />
    <el-table-column prop="goodsName" label="商品单价">
      <template #default="scope">
        {{ scope.row.goodsPrice + " 元 / " + scope.row.goodsUnit }}
      </template>
    </el-table-column>
    <el-table-column prop="goodsCount" label="销售数量" />
    <el-table-column prop="actuallyPaidAmount" label="实际收入金额(元)" />
    <el-table-column prop="payTime" label="结算时间">
      <template #default="scope">
        {{ utils.formatDate(scope.row.payTime) }}
      </template>
    </el-table-column>
    <el-table-column prop="createTime" label="创建时间">
      <template #default="scope">
        {{ utils.formatDate(scope.row.createTime) }}
      </template>
    </el-table-column>
    <el-table-column prop="updateTime" label="更新时间">
      <template #default="scope">
        {{ utils.formatDate(scope.row.updateTime) }}
      </template>
    </el-table-column>

    <el-table-column fixed="right" width="150" label="操作">
      <template #default="scope">
        <el-button size="small" type="primary" plain @click="edit(scope.$index, scope.row)"
          >修改</el-button
        >
        <el-button
          size="small"
          type="danger"
          @click="remove(scope.$index, scope.row)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <div class="pagination-block">
    <el-pagination
      background
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50, 100, 500]"
      prev-text="上一页"
      next-text="下一页"
      :disabled="disabled"
      :background="background"
      layout="prev, pager, next, sizes, jumper,total,slot"
      v-model:total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    </el-pagination>
  </div>

  <el-dialog v-model="dialogFormVisible" destroy-on-close title="销售记录">
    <el-form ref="formRef" :model="form">
      <el-form-item label="商品编码" :label-width="formLabelWidth">
        <el-select
          v-model="form.goodsCode"
          placeholder="请选择商品编码"
          filterable
          clearable
          reserve-keyword
          @clear="selectClear"
          :loading="loading"
        >
          <el-option
            v-for="item in options"
            @click.native="selectChange(item)"
            :key="item.code"
            :label="item.code + ' - ' + item.name"
            :value="item.code"
          >
            <span style="float: left">{{ item.code }}</span>
            <span style="float: right; font-size: 13px">{{ item.name }}</span>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="商品名称" :label-width="formLabelWidth">
        <el-input
          readonly
          disabled
          v-model="form.goodsName"
          placeholder="只读"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="单价" :label-width="formLabelWidth">
        <el-input-number
          type="number"
          readonly
          disabled
          v-model="form.goodsPrice"
          min="0"
          maxlength="18"
          placeholder="只读"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="单位" :label-width="formLabelWidth">
        <el-input
          readonly
          disabled
          v-model="form.goodsUnit"
          maxlength="128"
          placeholder="只读"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="数量" :label-width="formLabelWidth">
        <el-input-number
          @change="countChange"
          v-model="form.goodsCount"
          maxlength="128"
          min="1"
          placeholder="数量"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="结算时间" :label-width="formLabelWidth">
        <el-date-picker
          v-model="form.payTime"
          type="datetime"
          placeholder="请输入结算时间"
        />
      </el-form-item>
      <el-form-item label="支付金额" :label-width="formLabelWidth">
        <el-input-number
          placeholder="请输入支付金额"
          min="0"
          v-model="form.actuallyPaidAmount"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="id" :label-width="formLabelWidth" v-show="false">
        <el-input v-model="form.idSalesRecord" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="saveOrUpdate"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { Timer } from "@element-plus/icons-vue";
import { dbConnect } from "@/utils/sqlUtils.js";
import { reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import * as utils from "@/utils/utils.js";
import dayjs from "dayjs";

const dialogFormVisible = ref(false);
const tableData = reactive([]);
const formLabelWidth = "140px";
const formRef = ref({});
const total = ref(0);
const pageNo = ref(1);
const pageSize = ref(10);

const loading = ref(false);
const options = reactive([]);

const form = reactive({
  idSalesRecord: "",
  idGoods: 1,
  goodsCode: "",
  goodsName: "",
  goodsPrice: 0,
  goodsUnit: "",
  goodsCount: 1,
  payStatus: 0,
  goodsTotalAmount: "",
  payTime: new Date(),
  actuallyPaidAmount: 0,
  createTime: {},
  updateTime: {},
});

resetTotal();

search();

loadGoodsData();

function loadGoodsData() {
  dbConnect.all("select * from goods", (err, row) => {
    options.splice(0);
    options.push(...row);
  });
}

function countChange() {
  form.actuallyPaidAmount = (form.goodsPrice * form.goodsCount).toFixed(2);
}

function selectChange(item) {
  form.goodsCode = item.code;
  form.goodsName = item.name;
  form.idGoods = item.idGoods;
  form.goodsPrice = item.price;
  form.goodsUnit = item.unit;
  form.actuallyPaidAmount = (form.goodsPrice * form.goodsCount).toFixed(2);
}

function selectClear() {
  form.goodsCode = null;
  form.goodsName = null;
  form.idGoods = null;
  form.goodsPrice = null;
  form.goodsUnit = null;
  form.actuallyPaidAmount = null;
}

function resetTotal() {
  dbConnect.all(
    "select count(1) as count from sales_record where type = 1",
    (err, row) => {
      total.value = row[0].count;
    }
  );
}

function handleSizeChange(pageSize) {
  search();
}

function handleCurrentChange(pageNo) {
  search();
}

function edit(index, row) {
  form.idSalesRecord = row.idSalesRecord;
  form.idGoods = row.idGoods;
  form.goodsCode = row.goodsCode;
  form.goodsName = row.goodsName;
  form.goodsPrice = row.goodsPrice;
  form.goodsUnit = row.goodsUnit;
  form.goodsCount = row.goodsCount;
  form.payTime = utils.formatDate(row.payTime);
  form.actuallyPaidAmount = row.actuallyPaidAmount;
  dialogFormVisible.value = true;
}

function saveOrUpdate() {
  if (utils.isNotEmpty(form.idSalesRecord)) {
    let updateSql = `UPDATE sales_record SET goodsCode=?, goodsName=?, goodsPrice=?, goodsUnit=?, goodsCount=?,payTime=?, actuallyPaidAmount=?, updateTime=?， year=?, month=?, day=? WHERE idSalesRecord = ?`;
    dbConnect
      .prepare(updateSql, [
        form.goodsCode,
        form.goodsName,
        form.goodsPrice,
        form.goodsUnit,
        form.goodsCount,
        dayjs(form.payTime).toDate().getTime(),
        form.actuallyPaidAmount,
        new Date().getTime(),
        utils.getYear(dayjs(form.payTime).toDate()),
        utils.getFullMonth(dayjs(form.payTime).toDate()),
        utils.getFullDay(dayjs(form.payTime).toDate()),
        form.idSalesRecord,
      ])
      .run((err) => {
        if (err == null) {
          ElMessage({
            message: "修改成功",
            type: "success",
          });
          dialogFormVisible.value = false;
          search();
        } else {
          ElMessage({
            message: "修改失败" + err,
            type: "error",
          });
        }
      });
    form.name = null;
    form.unitPrice = null;
    form.remark = null;
    form.tableNo = null;
    form.idBoardGameTable = null;
    return;
  }

  let insertsql = `INSERT INTO sales_record (idGoods, goodsCode,goodsName,goodsPrice,goodsUnit,goodsCount,payTime,actuallyPaidAmount,updateTime,createTime, year,month,day,type) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?);`;
  dbConnect
    .prepare(insertsql, [
      form.idGoods,
      form.goodsCode,
      form.goodsName,
      form.goodsPrice,
      form.goodsUnit,
      form.goodsCount,
      dayjs(form.payTime).toDate().getTime(),
      form.actuallyPaidAmount,
      new Date().getTime(),
      new Date().getTime(),
      utils.getYear(dayjs(form.payTime).toDate()),
      utils.getFullMonth(dayjs(form.payTime).toDate()),
      utils.getFullDay(dayjs(form.payTime).toDate()),
      1,
    ])
    .run((err) => {
      if (err == null) {
        ElMessage({
          message: "新增成功",
          type: "success",
        });
        form.name = null;
        form.unitPrice = null;
        form.remark = null;
        form.tableNo = null;
        form.idBoardGameTable = null;
        dialogFormVisible.value = false;
        search();
      } else {
        ElMessage.error("新增失败" + err);
      }
    });
}

function search(showMessage) {
  resetTotal();
  dbConnect.all(
    "select * from sales_record where type = 1 order by updateTime desc LIMIT " +
      pageSize.value +
      " OFFSET " +
      (pageNo.value - 1) * pageSize.value,
    function (err, row) {
      if (utils.isNotEmpty(err)) {
        ElMessage({
          type: "error",
          message: "查询失败" + err,
        });
      } else {
        if (showMessage) {
          ElMessage({ type: "success", message: "查询成功" });
        }
        tableData.splice(0);
        tableData.push(...row);
      }
    }
  );
}

function remove(index, row) {
  ElMessageBox.confirm("是否删除该数据", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    let removeSql = `DELETE FROM sales_record WHERE idSalesRecord = ?`;
    dbConnect.prepare(removeSql, [row.idSalesRecord]).run(() => {
      ElMessage({
        type: "success",
        message: "删除完成",
      });
      search();
    });
  });
}
</script>


<style scoped>
.el-button--text {
  margin-right: 15px;
}
.el-select {
  width: 300px;
}
.el-input {
  width: 300px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}

.pagination-block {
  margin-top: 10px;
}
</style>